<template>
  <div class="app-container dialog-w80">
    <div class="customContainer">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-date-picker v-model="pickerDate" value-format="yyyy.MM.dd" type="daterange" align="right" unlink-panels range-separator="-"
            start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select filterable placeholder="仓库" v-model="formInline.house_id">
            <el-option v-for="item in house_list" :key="item.house_id" :label="item.name" :value="item.house_id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="订单状态:" v-model="formInline.status" filterable>
            <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="formInline.no" placeholder="请输入采购单号" @keyup.enter.native="searchClick">
          </el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>

      <!-- 列表 -->
      <el-table highlight-current-row :data="list" border size="small" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="36"></el-table-column>
        <el-table-column align="center" label='序号' width="50">
          <template slot-scope="scope">
            <span class="indexColor">{{scope.$index+1+(currentPage-1)*20}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status==0">待审核</span>
            <span v-if="scope.row.status==1">待确认</span>
            <span v-if="scope.row.status==2">待发货</span>
            <span v-if="scope.row.status==3">部分收货</span>
            <span v-if="scope.row.status==4">订单完结</span>
            <span v-if="scope.row.status==5">收货完成</span>
            <span v-if="scope.row.status==6">订单取消</span>
            <span v-if="scope.row.status==8">待收货</span>
            <span v-if="scope.row.status==9">申请退货中</span>
            <span v-if="scope.row.status==10">退货中</span>
            <span v-if="scope.row.status==11">退货完成</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="下单时间" prop="creat_time"></el-table-column>
        <el-table-column align="center" label="采购订单编号">
          <template slot-scope="scope">
            <el-button @click="get_order_info(scope.row.id,scope.$index,scope.row.status,scope.row.order_id)" type="text" size="small">{{scope.row.order_id}}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="当前操作部门">
          <template slot-scope="scope">
            供货商
          </template>
        </el-table-column>
        <el-table-column align="center" label='到货差额'>
          <template slot-scope="scope">
            {{scope.row.arrive_gift - scope.row.total_gift}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="入库时间" prop="company_name">
          <template slot-scope="scope">
            {{scope.row.update_time=='0'?'----.--.--':(scope.row.update_time)}}
          </template>
        </el-table-column>
        <el-table-column align="center" label='备注' prop="remark"></el-table-column>
        <!-- 列表的操作按钮 -->
        <el-table-column align="center" label="操作" width="200">
          <template slot-scope="scope">
            <el-button v-if="(scope.row.status !=  10)&&(scope.row.status !=  11)" :disabled="(scope.row.status !=  4)&&(scope.row.status != 5)"
              @click="returnApplyClick(scope.row.id,scope.$index,scope.row.status)" type="primary" size="mini">退货</el-button>
            <el-button v-if="(scope.row.status ==  10)" @click="returnInfoClick(scope.row.id,scope.$index)" type="primary" size="mini">完善退货信息</el-button>
            <el-button v-if="(scope.row.status ==11)" @click="returnInfoClick(scope.row.id)" type="primary" size="mini">查看退货信息</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 采购入库弹框 -->
    <el-dialog :close-on-click-modal="false" class="dialog_table" title="采购入库" :visible.sync="detail_dialog">
      <div class="dialogInContainer" v-loading="dialogLoading">
        <span style="position:absolute;top:20px;left:180px">订单编号：{{order_id}}</span>
        <el-table highlight-current-row :data="infolist" v-loading.body="listLoading" border size="small" @selection-change="detailSelection">
          <el-table-column type="selection" width="36"></el-table-column>
          <el-table-column align="center" label='序号' width="50">
            <template slot-scope="scope">
              <span class="indexColor">{{scope.$index+1}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="图片" width="70">
            <template slot-scope="scope">
              <img :src="scope.row.thumb" width="50" height="50" alt="">
            </template>
          </el-table-column>
          <el-table-column align="center" label="礼品名称" prop="gift_name"></el-table-column>
          <el-table-column align="center" label="礼品编号" prop="gift_id"></el-table-column>
          <el-table-column align="center" label="箱规" prop="box_num"></el-table-column>
          <el-table-column align="center" label="三级分类" prop="type_name"></el-table-column>
          <el-table-column align="center" label="成本价" prop="money_sell"></el-table-column>
          <el-table-column align="center" label="供应商" prop="supplier_name"></el-table-column>
          <el-table-column align="center" label="礼品渠道" prop="type_name"></el-table-column>
          <el-table-column align="center" label="订单数" prop="total_num"></el-table-column>
          <el-table-column align="center" label="累计到货数" prop="arrive_num"></el-table-column>
          <el-table-column align="center" label="本次到货数">
            <template slot-scope="scope">
              <el-input type="number" @input="changeNum(scope.row)" onmousewheel="return false;" v-model="scope.row.now_arrive_num"
                :disabled="isDisabled||scope.row.is_del*1>0||scope.row.all_arrive" placeholder="数量">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="差异">
            <template slot-scope="scope">
              <span :class="scope.row.arrive_diff==0?'':'danger'">{{scope.row.arrive_diff}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="退货数" prop="return_num"></el-table-column>
          <el-table-column align="center" label="审核结果" prop="order_num">
            <template slot-scope="scope">
              <span v-if="scope.row.status==4">结束</span>
              <span v-else-if="scope.row.is_del==0&&scope.row.status==0">审核中</span>
              <span v-else-if="scope.row.is_del==0&&scope.row.status!=0">通过</span>
              <span v-else class="danger">未通过</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="备注">
            <template slot-scope="scope">礼品部:{{scope.row.remark_g}}<br />
              采购部:{{scope.row.remark_p}}</template>
          </el-table-column>
        </el-table>
        <!-- 自定义底部 -->
        <br>
        <div class="bottom_box">
          <el-button v-if="infoSelection.length>0 && !isDisabled" :disabled="isDisabled" size="small" type="primary" @click="allArriveClick()">无差异到货</el-button>
          <el-button v-if="infoSelection.length>0 && !isDisabled" :disabled="isDisabled" size="small" type="primary" @click="resetClick()">重置</el-button>
          <el-button class="pull-right" :disabled="isDisabled" size="small" type="primary" :loading="btnLoding" @click="saveClick()">确认提交</el-button>
          <p class="pull-right total_box">
            <span class="total">合计</span>
            <span>订单数：{{allOrder}}</span>
            <span>累计到货数：{{allArrive}}</span> 　
            <span>本次到货数：{{thisArrive}}</span>
            <span>差异：<span :class="allArriveDiff==0?'':'danger'">{{allArriveDiff}}</span></span>
            <span>退货数：{{allReturn}}</span>
          </p>
        </div>
      </div>
    </el-dialog>
    <!-- 退货申请弹框 -->
    <el-dialog :close-on-click-modal="false" title="退货申请" :visible.sync="returnApplyDialog" append-to-body>
      <div class="dialogInContainer" v-loading="dialogLoading">
        <el-table highlight-current-row :data="returnApplyList" size="small" border>
          <el-table-column align="center" label="序号" width="60">
            <template slot-scope="scope">
              <span class="indexColor">{{scope.$index+1}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="订单状态">
            <template slot-scope="scope">
              {{stateName}}
            </template>
          </el-table-column>
          <el-table-column align="center" property="gift_name" label="退货礼品名称"></el-table-column>
          <el-table-column align="center" property="gift_id" label="礼品编号"></el-table-column>
          <el-table-column align="center" property="arrive_num" label="可退货数量"></el-table-column>
          <el-table-column align="center" label="退货数量">
            <template slot-scope="scope">
              <el-input type="number" onmousewheel="return false;" v-model="scope.row.return_num" placeholder="数量"></el-input>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-form :inline="true" class="demo-form-inline pull-left" size="small">
            <el-form-item>
              <el-input v-model="return_remark" placeholder="备注信息"></el-input>
            </el-form-item>
          </el-form>
          <div style="overflow:hidden">
            <el-button class="pull-right" type="primary" @click="returnApplySaveClick()" size="small"> 提 交
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
    <!-- 退货信息弹框 -->
    <el-dialog :close-on-click-modal="false" title="退货信息" :visible.sync="returnInfoDialog" append-to-body>
      <el-form :inline="true" class="demo-form-inline" size="small">
        <el-form-item label="物流公司">
          <el-input :disabled="isDisabled" v-model="logistics_company" placeholder="物流公司"></el-input>
        </el-form-item>
        <el-form-item class="pull-right" label="物流单号">
          <el-input :disabled="isDisabled" v-model="logistics_no" placeholder="物流单号"></el-input>
        </el-form-item>
      </el-form>
      <el-table highlight-current-row :data="returnInfoList" size="small" border>
        <el-table-column align="center" label="序号" width="60">
          <template slot-scope="scope">
            <span class="indexColor">{{scope.$index+1}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" property="name" label="退货礼品名称"></el-table-column>
        <el-table-column align="center" property="gift_id" label="礼品编号"></el-table-column>
        <el-table-column align="center" property="order_num" label="退货礼品数量"></el-table-column>
        <el-table-column align="center" property="pay_money" label="退货礼品金额">
          <template slot-scope="scope">
            {{scope.row.pay_money*scope.row.order_num}}
          </template>
        </el-table-column>
        <el-table-column align="center" property="creat_time" label="退货时间"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isDisabled" type="primary" @click="returnInfoSaveClick()" size="small"> 提 交
        </el-button>
      </div>
    </el-dialog>
    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
        layout="prev, pager, next, jumper" :total="totalDataNumber">
      </el-pagination>
      <div class="pull-right">
        <el-button :disabled="exportForm.length==0" type="primary" size="small" @click="exportClick()" :loading="exportLoading">采购单导出
          <count-down ref="cd" />
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  house,
  getList,
  getPage,
  getExport,
  getinfoList,
  save,
  getReturnApplyList,
  returnApplySave,
  getReturnInfoList,
  returnInfoSave
} from '@/api/storage_control/purchase.js';
import { pickerOptionsSixMonth, pickerDateSixMonth, optionMaxTime198 } from '@/utils';
export default {
  data() {
    return {
      exportLoading: false,
      btnLoding: false,
      dialogLoading: false,
      listLoading: false,
      status: [
        { id: -1, name: '全部' },
        { id: 0, name: '待审核' },
        { id: 1, name: '待确认' },
        { id: 2, name: '待发货' },
        { id: 3, name: '部分收货' },
        { id: 4, name: '订单完结' },
        { id: 5, name: '收货完成' },
        { id: 6, name: '订单取消' },
        { id: 8, name: '待收货' },
        { id: 9, name: '申请退货中' },
        { id: 10, name: '退货中' },
        { id: 11, name: '退货完成' }
      ],
      currentPage: 1,
      returnApplyDialog: false,
      totalDataNumber: 0,
      returnInfoDialog: false,
      returnInfoList: [],
      order_id: '',
      logistics_company: '',
      logistics_no: '',
      editId: '',
      editIndex: '',
      return_remark: '',
      stateName: '',
      formInline: {
        house_id: 0,
        no: '',
        start: '',
        end: '',
        status: 8
      },
      detail_dialog: false,
      infolist: [],
      house_list: [],
      returnApplyList: [],
      list: null,
      saveForm: {
        order_id: this.editId,
        data: []
      },
      pickerOptions: pickerOptionsSixMonth(),
      pickerDate: pickerDateSixMonth(),
      exportForm: '',
      infoSelection: [],
      isDisabled: false
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (!vm.list) {
        vm.gethouse();
        vm.searchClick();
      }
    });
  },
  methods: {
    resetClick() {
      this.infoSelection.forEach(val1 => {
        this.infolist.forEach(val2 => {
          if (val1.id == val2.id) {
            val2.now_arrive_num = '';
          }
        });
      });
    },
    allArriveClick() {
      this.infoSelection.forEach(val1 => {
        this.infolist.forEach(val2 => {
          if (val1.id == val2.id) {
            val2.now_arrive_num = 0;
            if (val2.is_del == 0) {
              val2.now_arrive_num = val2.total_num * 1 - val2.arrive_num * 1 == 0 ? '' : val2.total_num * 1 - val2.arrive_num * 1;
              this.changeNum(val2);
            }
          }
        });
      });
    },
    detailSelection(val) {
      this.infoSelection = val;
    },
    returnInfoClick(id, index) {
      this.editId = id;
      this.isDisabled = index ? false : true;
      this.editIndex = index ? index : '';
      getReturnInfoList({ order_id: id }).then(response => {
        this.returnInfoList = response;
        this.logistics_company = response[0].logistics_company;
        this.logistics_no = response[0].logistics_no;
      });
      this.returnInfoDialog = true;
    },
    returnInfoSaveClick() {
      if (this.logistics_company == '' || this.logistics_no == '') {
        this.$message({ type: 'error', message: '请填写完整物流信息' });
        return;
      }
      let data = {
        order_id: this.editId,
        name: this.logistics_company,
        no: this.logistics_no
      };
      returnInfoSave(data).then(response => {
        this.$message({
          type: response.code == 1 ? 'success' : 'error',
          message: response.message
        });
        if (response.code == 1) {
          this.returnInfoDialog == false;
        }
      });
    },
    returnApplySaveClick() {
      let ok = true;
      for (let i = 0; i < this.returnApplyList.length; i++) {
        if (
          this.returnApplyList[i].return_num == '' ||
          this.returnApplyList[i].return_num == null ||
          this.returnApplyList[i].return_num < 0 ||
          !/^\d+$/.test(this.returnApplyList[i].return_num)
        ) {
          ok = false;
          this.$message({ type: 'error', message: '请把退货数量填写完整,退货数量只能为整数' });
          break;
        }
        if (this.returnApplyList[i].return_num > this.returnApplyList[i].arrive_num * 1) {
          ok = false;
          this.$message({ type: 'error', message: '退货数量大于可退货数' });
          break;
        }
      }
      if (ok) {
        let data = {
          order_id: this.editId,
          remark: this.return_remark,
          is_return: 1,
          list: []
        };
        for (let i = 0; i < this.returnApplyList.length; i++) {
          data.list.push({
            gift_id: this.returnApplyList[i].gift_id,
            order_num: this.returnApplyList[i].return_num,
            look_money: this.returnApplyList[i].money_sell
          });
        }
        returnApplySave(data).then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.list[this.editIndex].status = 9;
            this.returnApplyDialog = false;
          }
        });
      }
    },
    returnApplyClick(id, index, status) {
      this.dialogLoading = true;
      this.editId = id;
      this.editIndex = id ? index : '';
      this.stateName = status == 4 ? '订单完结' : '收货完成';
      getReturnApplyList({ order_id: id }).then(response => {
        this.returnApplyList = response;
        this.dialogLoading = false;
      });
      this.returnApplyDialog = true;
    },
    saveClick() {
      let flat = true;
      this.saveForm.data = [];
      // 过滤掉全部到货的数组
      let new_infolist = this.infolist.filter(function(item) {
        return item.total_num != item.arrive_num;
      });
      this.infolist.forEach((val, index) => {
        if ((!val.all_arrive && val.is_del == 0 && val.now_arrive_num == '') || (!val.all_arrive && val.is_del == 0 && val.now_arrive_num == null)) {
          return;
        } else {
          if (Number(val.arrive_num) + Number(val.now_arrive_num) > Number(val.total_num)) {
            flat = false;
            // return;
          } else {
            this.saveForm.data.push({ gift_id: val.gift_id, arrive_num: val.now_arrive_num * 1, look_money: val.money_sell });
          }
        }
      });
      if (flat == false) {
        this.$message({ type: 'error', message: '到货数不能大于订单数!' });
        return;
      }
      if (this.saveForm.data.length == this.infolist.length) {
        this.$confirm('此操作提交, 是否继续?', '提示').then(() => {
          this.btnLoding = true;
          save(this.saveForm)
            .then(response => {
              this.$message({
                type: response.code == 1 ? 'success' : 'error',
                message: response.message
              });
              if (response.code == 1) {
                this.btnLoding = false;
                this.detail_dialog = false;
                this.handleCurrentChange(this.currentPage);
              }
            })
            .catch(() => {
              this.btnLoding = false;
            });
        });
      } else {
        this.$message({ type: 'error', message: '请将所有信息填写完整（未到货的请填0）' });
        return;
      }
    },
    handleSelectionChange(val) {
      this.exportForm = val;
      console.log(this.exportForm);
    },
    // 导出
    exportClick() {
      const idArr = [];
      this.exportForm.forEach(function(val, index) {
        idArr.push(val.id);
      });
      // if (idArr.length > 1) {
      //     this.$message({ type: 'error', message: '采购入库导出目前仅支持“单选”' })
      //     return;
      // }
      getExport({ type: 1, order_id: idArr.join(',') });
      this.exportLoading = true;
      this.$refs.cd.countDownF(30).then(() => {
        this.exportLoading = false;
      });
    },
    // 打开订单详情
    get_order_info(id, index, status, order_id) {
      this.dialogLoading = true;
      this.detail_dialog = true;
      this.order_id = order_id;
      this.saveForm.order_id = id;
      getinfoList({ order_id: id }).then(response => {
        response.forEach(val => {
          val.money_sell *= 1;
          val.supplier_name = val.supplier_name ? val.supplier_name : '-';
          val.type_name = val.type == 1 ? '供应商' : '中央仓';
          val.all_arrive = val.total_num == val.arrive_num ? true : false;
          val.arrive_diff = val.now_arrive_num * 1 + val.arrive_num * 1 - val.total_num * 1;
        });
        this.infolist = response;
        if (response[0].status == 3 || response[0].status == 8) {
          this.isDisabled = false;
        } else {
          this.isDisabled = true;
        }
        this.dialogLoading = false;
      });
    },
    gethouse() {
      house().then(response => {
        this.house_list = response;
      });
    },
    searchClick() {
      optionMaxTime198(this.pickerDate).then(() => {
        //最大可选择时间区间
        this.formInline.start = this.pickerDate ? this.pickerDate[0] : '';
        this.formInline.end = this.pickerDate ? this.pickerDate[1] : '';
        this.fetchData();
      });
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      this.currentPage = 1;
      getPage(this.formInline)
        .then(response => {
          this.totalDataNumber = response.page * 20;
          getList(this.formInline).then(response => {
            response.forEach(val => {
              val.money_cost = (val.money_cost / 1000000).toFixed(2) * 1;
            });
            this.list = response;
            this.listLoading = false;
          });
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    // 分页
    handleCurrentChange(val) {
      this.listLoading = true;
      getList(this.formInline, val).then(response => {
        response.forEach(val => {
          val.money_cost = (val.money_cost / 1000000).toFixed(2) * 1;
        });
        this.list = response;
        this.listLoading = false;
      });
    },
    //合计
    totalMethods(list, key) {
      return list.reduce((prev, list) => prev + (list.is_del === '0' ? list[key] / 1 : 0), 0);
    },
    //输入框中的值变化时重新计算差异
    changeNum(row) {
      row.arrive_diff = row.arrive_num * 1 + row.now_arrive_num * 1 - row.total_num * 1;
    }
  },
  computed: {
    thisArrive: function() {
      return this.totalMethods(this.infolist, 'now_arrive_num');
    },
    allOrder: function() {
      return this.totalMethods(this.infolist, 'order_num');
    },
    allArrive: function() {
      return this.totalMethods(this.infolist, 'arrive_num');
    },
    allArriveDiff: function() {
      return this.totalMethods(this.infolist, 'arrive_diff');
    },
    allReturn: function() {
      return this.totalMethods(this.infolist, 'return_num');
    }
  }
};
</script>